package com.codeyang.controller;

import com.codeyang.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 描述: 支付服务接口
 *
 * @author CodeYang_Site
 * @version 2021/6/2 17:39
 */
@Api(tags = "支付服务管理接口")
@RestController
@RequestMapping
public class PayController {


    @Autowired
    private PayService payService;

    @PostMapping("p/order/pay")
    @ApiOperation("根据订单号 生成二维码")
    public ResponseEntity<String> createQrCode(@RequestBody Map<String, String> map) {
        //拿到订单号
        String orderNumber = map.get("orderNumber");

        String QRCode = payService.toPay(orderNumber);

        return ResponseEntity.ok(QRCode);
    }

    // 通知地址文档: https://opendocs.alipay.com/open/194/103296

    @PostMapping("payNotify")
    @ApiOperation("接收支付宝的回调")
    public ResponseEntity<String> payNotify(@RequestParam Map<String, String> map) {
        System.out.println(map);
        System.out.println("回调来了");
        //拿一下交易状态
        if (map.get("trade_status").equals("TRADE_SUCCESS")) {
            //交易成功,但是要验签名一下,以防伪造请求
            Boolean flag = payService.checkPay(map);
            if (flag) {
                //交易成功+验签成功了,就要修改订单状态了

                payService.changeOrderStatus(map.get("out_trade_no"));
                return ResponseEntity.ok("成功");
            }
        }
        return ResponseEntity.ok("伪造请求,我记住你了");
    }


    @PostMapping("confirmPayStatus")
    @ApiOperation("查询支付宝 确认订单状态")
    public Boolean confirmPayStatus(@RequestParam String orderNum) {
        return payService.confirmPayStatus(orderNum);

    }
}
